package com.epfresh.views.dialog;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.T;
import com.epfresh.bean.ListGoods;
import com.epfresh.utils.FormatUtil;

/**
 * Created by wzh on 16-7-13.
 */
public class DeliveryAddCartDialog extends BaseDialogView implements View.OnClickListener {

    public interface OnAddCartListener {
        public void onAddCart(double cnt);
    }

    TextView tvUnitPrice;
    TextView tvInventory;
    TextView tvLeast;
    public EditText edCnt;
    ImageView ivLogo;
    TextView tvChargeUnit;
    TextView tvIntro;
    TextView tvPackage;
    public ListGoods goodsDetail;

    OnAddCartListener onAddCartListener;
    //    TextWatcher ta;
    double min = 0.01;
    double max = 9999999;
    double incr = 0.01;

    boolean isSureEnable = true;


    public DeliveryAddCartDialog(Context context) {
        super(context);

        init();
    }

    public OnAddCartListener getOnAddCartListener() {
        return onAddCartListener;
    }

    public void setOnAddCartListener(OnAddCartListener onAddCartListener) {
        this.onAddCartListener = onAddCartListener;
    }

    public boolean isSureEnable() {
        return isSureEnable;
    }

    public void setSureEnable(boolean sureEnable) {
        isSureEnable = sureEnable;
    }

    @Override
    public void initBefore() {
        setGravity(Gravity.BOTTOM);
    }

    @Override
    protected void initAnim() {
        super.initAnim();
    }

    private void init() {

        View v = LayoutInflater.from(context).inflate(R.layout.item_add_cart, contentContainer);

        tvUnitPrice = (TextView) v.findViewById(R.id.tv_unit_price);
        tvInventory = (TextView) v.findViewById(R.id.tv_inventory);
        tvLeast = (TextView) v.findViewById(R.id.tv_min);
        tvChargeUnit = (TextView) v.findViewById(R.id.tv_charge_unit);
        tvIntro = (TextView) v.findViewById(R.id.tv_intro);
        edCnt = (EditText) v.findViewById(R.id.ed_price);
        ivLogo = (ImageView) v.findViewById(R.id.iv_img);
        tvPackage = (TextView) v.findViewById(R.id.tv_package);
        v.findViewById(R.id.iv_add).setOnClickListener(this);
        v.findViewById(R.id.iv_remove).setOnClickListener(this);
        v.findViewById(R.id.tv_sure_cart).setOnClickListener(this);
        v.findViewById(R.id.iv_cancel).setOnClickListener(this);

//        TextWatcher ta = new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
//
//                String s = editable.toString();
//                edCnt.removeTextChangedListener(this);
//                if ("".equals(s)) {
//                    edCnt.setText(min + "");
//                    edCnt.setSelection(edCnt.getText().toString().length());
//                    edCnt.addTextChangedListener(this);
//                    return;
//                }
//                int numberFlag = Integer.valueOf(s);
//                if (numberFlag < min)
//                    numberFlag = min;
////                if ("".equals(s)){
////                    edCnt.setText(standardNumber(numberFlag)+"");
////                }
//                if ((numberFlag - min) % incr > 0) {
//                    numberFlag = (numberFlag - min) / incr + incr + min;
//                }
//
//                edCnt.setText(numberFlag + "");
//                edCnt.setSelection(edCnt.getText().toString().length());
///*                if (VerificationUtils.isNumeric(s)){
//                    int cnt = Integer.valueOf(s);
//                    if (cnt < numberFlag){
//                        edCnt.setText(""+numberFlag);
//                        edCnt.setText(standardNumber(numberFlag)+"");
//                    }else if (cnt > numberFlag){
//                        edCnt.setText(""+max);
//                        edCnt.setText(standardNumber(min)+"");
//                    }
//                }*/
//                edCnt.addTextChangedListener(this);
//            }
//        };
//        edCnt.addTextChangedListener(ta);
//        edCnt.setEnabled(false);


        TextWatcher ta = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                String s = editable.toString();
                edCnt.removeTextChangedListener(this);
                if ("".equals(s)) {
//                    edCnt.setText(min + "");
//                    edCnt.setSelection(edCnt.getText().toString().length());
//                    edCnt.addTextChangedListener(this);
//                    updateIntro(min);
//                    return;
                    s = "0";
                }
                Double numberFlag = Double.valueOf(s);
//                if (numberFlag < min)
//                    numberFlag = min;
                updateIntro(numberFlag);
//                if ((numberFlag - min) % incr > 0) {
//                    numberFlag = (numberFlag - min) / incr + incr + min;
//                }
//
//                edCnt.setText(numberFlag + "");
//                edCnt.setSelection(edCnt.getText().toString().length());
/*                if (VerificationUtils.isNumeric(s)){
                    int cnt = Integer.valueOf(s);
                    if (cnt < numberFlag){
                        edCnt.setText(""+numberFlag);
                        edCnt.setText(standardNumber(numberFlag)+"");
                    }else if (cnt > numberFlag){
                        edCnt.setText(""+max);
                        edCnt.setText(standardNumber(min)+"");
                    }
                }*/
                edCnt.addTextChangedListener(this);
            }
        };
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 99999;
        edCnt.setFilters(new InputFilter[]{cashierInputFilter});
//        edCnt.addTextChangedListener(ta);
        setCancelable(true);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                add(true);
                break;

            case R.id.iv_remove:
                add(false);
                break;

            case R.id.tv_sure_cart:

                sure();
                break;
            case R.id.iv_cancel:
                Log.i("afasdf", "isShowing:" + isShowing());
                Log.i("afasdf", "isDismissing:" + isDismissing);
                dismiss();
                Log.e("afasdf", "isShowing:" + isShowing());
                Log.e("afasdf", "isDismissing:" + isDismissing);
                break;


        }
    }


    public void add(boolean isAdd) {


        String t = edCnt.getText().toString();
        double cnt = min;
        double incr = goodsDetail.getIncr();
//        if (cnt < min)
//            cnt = min;
        try {
            cnt = Double.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (isAdd) {
                //cnt++;
                if (goodsDetail != null /*&& cnt < goodsDetail.getInventory()*/)
                    cnt = FormatUtil.countAdd(cnt, goodsDetail.getIncr());
            } else {
                cnt = FormatUtil.countSubtract(cnt, goodsDetail.getIncr());

            }
            if (cnt < min) {
                cnt = min;
            }
            updateIntro(cnt);
            edCnt.setText(FormatUtil.subZeroAndDot(cnt + ""));
            edCnt.setSelection(edCnt.getText().toString().length());
        }

    }

    public void sure() {
        boolean legitimate = isLegitimate();

        Log.e("legitimate","legitimate:"+legitimate);
        if (!legitimate){
            return;
        }
        String t = edCnt.getText().toString();
        double cnt = min;
        try {
            cnt = Double.valueOf(t);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (FormatUtil.remainderZero(min,cnt) > 0)
            {
                T.toast("数量少于最小起订量");
                cnt = min;
            }
            if (FormatUtil.remainderZero(cnt,max) > 0){
                T.toast("数量超过库存");
                cnt = max;
            }

            if (legitimate) {
                if (onAddCartListener != null) {
                    if (cnt < 0.01) {
                        T.toast("请添加数量");
                    } else
                        onAddCartListener.onAddCart(cnt);
                }
            }
        }


    }


    public boolean isLegitimate() {
        boolean isLegitimate = true;
        String s = edCnt.getText().toString();
        if ("".equals(s)) {
            edCnt.setText(FormatUtil.subZeroAndDot(min + ""));
            edCnt.setSelection(edCnt.getText().toString().length());
            return false;
        }
        double numberFlag = Double.valueOf(s);

//        if (numberFlag < min)
//            numberFlag = min;

        incr = incr == 0 ? min : incr;
        if (FormatUtil.isRemainder(numberFlag, incr,min)) {
            numberFlag = FormatUtil.countFormat(numberFlag, incr,min);
            T.toast("已校准数量,请重新加入购物车");
            isLegitimate = false;
        }

        edCnt.setText(FormatUtil.subZeroAndDot(numberFlag + ""));
        updateIntro(numberFlag);
        edCnt.setSelection(edCnt.getText().toString().length());

        return isLegitimate;
    }


    public void show(ListGoods goodsDetail, double min) {
        this.goodsDetail = goodsDetail;

        tvIntro.setVisibility(View.INVISIBLE);
        if (goodsDetail != null) {

            tvUnitPrice.setText(goodsDetail.getPrice() + "");
            tvLeast.setText(FormatUtil.subZeroAndDot(goodsDetail.getMoq() + "") + goodsDetail.getUnit() + "起订");
            double price = goodsDetail.getPrice();

            tvInventory.setVisibility(View.GONE);
//            tvLeast.setVisibility(View.GONE);
            tvChargeUnit.setText(goodsDetail.getUnit());
            edCnt.setText(FormatUtil.subZeroAndDot(min + ""));
            tvPackage.setText(goodsDetail.getPack());
            updateIntro(min);
            edCnt.setSelection(edCnt.getText().toString().length());
            String url = goodsDetail.getThumbnail();
            ImageLoader.getInstance().displayImage(url, ivLogo);
            super.show();
        }
    }

    public void updateIntro(double count) {
        tvIntro.setVisibility(View.INVISIBLE);
        if (this.goodsDetail != null) {
            double incr = goodsDetail.getIncr();

            if (incr < 0.01) {
                incr = 0.01;
            }
            String container = goodsDetail.getPackageContainer();
            String unit = goodsDetail.getPackageUnit();
            String chargeUnit = goodsDetail.getUnit();

            double num = FormatUtil.countDivide(count , incr);
            if ("散货".equals(container)) {
                if (chargeUnit != null && chargeUnit.equals(unit)) {
                    return;
                }
                tvIntro.setText("已选: " + FormatUtil.subZeroAndDot(count + "") + chargeUnit + "( " + FormatUtil.subZeroAndDot(num + "") + unit + " )");
            } else {
                if (chargeUnit != null && chargeUnit.equals(container)) {
                    return;
                }
                tvIntro.setText("已选: " + FormatUtil.subZeroAndDot(count + "") + chargeUnit + "( " + FormatUtil.subZeroAndDot(num + "") + container + " )");
            }
            tvIntro.setVisibility(View.VISIBLE);
        }
    }

    public double calMin(ListGoods goodsDetail) {
        if (goodsDetail != null) {
            double leastCount = goodsDetail.getMoq();
            if (leastCount < 0.01) {
                leastCount = 0.01;
            }
            min = leastCount;
            incr = goodsDetail.getIncr();
            if (min < 0.01){
                min = 0.01;
            }
            if (incr < 0.01){
                incr = 0.01;
            }
        }
        return min;

    }


//    public double standardNumber(double flag){
//        if(goodsDetail.getIncr()==0){
//            return flag;
//        }
//        double standardNumber;
//        double remainderNumber;
//        double timesNumber;
//        timesNumber = (flag/goodsDetail.getIncr())*(goodsDetail.getIncr());
//        remainderNumber = goodsDetail.getIncr();
//        if(timesNumber == flag){
//            remainderNumber = 0;
//        }
//        standardNumber = timesNumber + remainderNumber;
//        //DecimalFormat df = new DecimalFormat("#.00");
//        //df.format(standardNumber);
//        standardNumber = new BigDecimal(standardNumber).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//        return standardNumber;
//    }
}
